<?php

  /*******************************
  技术支持： 唤梦科技
  website : http://www.dreammm.net
  QQ 75039960
  Mobile 18665802636
  ********************************/


function get_access_token()
{
     $tokenFile="./access_token.txt";
      $tokenFile2="./access_token2.txt";
     $data= json_decode(file_get_contents($tokenFile));
     if ( ! $data->expire_time    )
     {
          $jsonStr['expire_time'] = 1429182351;//time() + 3600; //保存1小时

           // $jsonStr['access_token'] = $access_token;
             $jsonStr['access_token'] = "none";

            $fp = fopen($tokenFile, "w"); //只写文件

            fwrite($fp, json_encode($jsonStr)); //写入json格式文件

            fclose($fp);
     }

      if($data->expire_time < time())
     {
        $appid = "wx2c84d0dcd05b00f1";   //应用ID
		$appsecret = "c4f82f8cad4c1448f1c918d6cc128f98";   //应用密钥
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$appsecret";

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$output = curl_exec($ch);
		curl_close($ch);

		$jsoninfo = json_decode($output, true);		//json转数组

         $logFile="./log.txt";
         $fp = fopen($logFile, "a");
          fwrite($fp, "\n");
         fwrite($fp,  time(). " update access_toaken " );
           fwrite($fp, "\n");

         fclose($fp);

		if( $jsoninfo['access_token'])
		{
            //$output['expire_time'] = 1429182352;//time() + 3600; //保存1小时
            $jsonStr['access_token'] =  $jsoninfo['access_token'];
            $jsonStr['expire_time'] = time() + 7200;
            $fp = fopen($tokenFile, "w"); //只写文件
            fwrite($fp, json_encode($jsonStr)); //写入json格式文件
            fclose($fp);

		}

	}// if($data->expire_time < time())


     //return $data['access_token']  ;  //incorrect
     return  $data->access_token;

}

function GetTokenTest($fromUsername,$toUsername){
	$textTpl = "<xml>
                <ToUserName><![CDATA[%s]]></ToUserName>
                <FromUserName><![CDATA[%s]]></FromUserName>
                <CreateTime>%s</CreateTime>
                <MsgType><![CDATA[%s]]></MsgType>
                <Content><![CDATA[%s]]></Content>
                <FuncFlag>0</FuncFlag>
                </xml>";                          //构造XML数据格式
	$msgType = "text";                         //定义响应消息类型text


	$access_token = get_access_token();
	 $contentStr = "token=: "  .  $access_token;


	$responseStr = sprintf($textTpl, $fromUsername, $toUsername, time(), $msgType, $contentStr);
    	//把格式化的字符串写入变量
    	echo $responseStr;                             //响应XML数据
}


?>